﻿using FastCode.Architecture;
using FastCode.DTO;
using FastCode.Models;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System.Text;

namespace FastCode.Controllers
{
    public class DBConfigController : ApiControllerBase<DBConfig>
    {

        /// <summary>
        /// 获取所有数据库
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<object> GetAllDb()
        {
            var allDb = await GetBaseQuery<DBConfig>().ToListAsync();
            //添加框架表
            allDb.Insert(0, new DBConfig
            {
                Id = 0,
                Name = "框架库",
            });
            return Msg.Success(allDb);
        }

        /// <summary>
        /// 获取数据库的表
        /// </summary>
        /// <param name="dBConfig"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<object> GetDbTables(DBConfig dBConfig)
        {
            try
            {

                //var item = await db.Queryable<DBConfig>().FirstAsync(x => x.Id == dBConfig.Id);
                //var testDb = new SqlSugarClient(new ConnectionConfig()
                //{
                //    ConnectionString = item.ConnectStr,
                //    DbType = item.EDBType,
                //    IsAutoCloseConnection = true
                //});

                var tableInfoList = new List<DbTableInfo>();
                //如果是框架库
                if (dBConfig.Id == 0)
                {
                    tableInfoList = db.DbMaintenance.GetTableInfoList();
                }
                else
                {
                    var testDb = await GetSqlClientAsync(dBConfig.Id);
                    tableInfoList = testDb.DbMaintenance.GetTableInfoList();
                }

                return Msg.Success(tableInfoList);

            }
            catch (Exception ex)
            {
                return Msg.Error(ex.Message);
            }
        }

        /// <summary>
        /// 获取数据库客户端
        /// </summary>
        /// <param name="dbConfigId"></param>
        /// <returns></returns>
        [NonAction]
        public async Task<SqlSugarClient> GetSqlClientAsync(int dbConfigId)
        {
            var item = await db.Queryable<DBConfig>().FirstAsync(x => x.Id == dbConfigId);
            var testDb = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = item.ConnectStr,
                DbType = item.EDBType,
                IsAutoCloseConnection = true
            });

            return testDb;
        }

        /// <summary>
        /// 获取表对应列信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<object> GetModelClass(DBConfigDTO dto)
        {
            SqlSugarClient? configDb;
            if (dto.Id == 0)
            {
                configDb = db;
            }
            else
            {
                configDb = await GetSqlClientAsync(dto.Id);
            }

            var columnInfos = configDb.DbMaintenance.GetColumnInfosByTableName(dto.TableName, false);


            StringBuilder classBuilder = new StringBuilder();


            if (!string.IsNullOrEmpty(dto.TableDescription))
            {
                classBuilder.AppendLine($"/// <summary>");
                classBuilder.AppendLine($"/// {dto.TableDescription}");
                classBuilder.AppendLine($"/// </summary>");
            }

            classBuilder.AppendLine($"public class {dto.TableName}");
            classBuilder.AppendLine("{");

            var attributeIndent = "    ";
            foreach (var item in columnInfos)
            {

                if (!string.IsNullOrEmpty(item.ColumnDescription))
                {
                    classBuilder.AppendLine($"{attributeIndent}/// <summary>");
                    classBuilder.AppendLine($"{attributeIndent}/// {item.ColumnDescription}");
                    classBuilder.AppendLine($"{attributeIndent}/// </summary>");

                }
                var cSharpType = DbTypeConverter.ConvertStringTypeToCSharpType(item.DataType);
                //ctype.Name
                //public String Name{ get; set;}
                var isNullable = item.IsNullable ? "?" : "";
                classBuilder.AppendLine($"{attributeIndent}public {cSharpType.Name}{isNullable} {item.DbColumnName} {{ get; set; }}");
            }

            classBuilder.AppendLine("}");

            return Msg.Success(classBuilder.ToString());
        }





        //protected virtual string GetPropertyTypeName(DbColumnInfo item)
        //{
        //    string text = ((item.PropertyType != null) ? item.PropertyType.Name : Context.Ado.DbBind.GetPropertyTypeName(item.DataType));
        //    if (text != "string" && text != "byte[]" && text != "object" && item.IsNullable)
        //    {
        //        text += "?";
        //    }

        //    if (text == "Int32")
        //    {
        //        text = (item.IsNullable ? "int?" : "int");
        //    }

        //    if (text == "String")
        //    {
        //        text = "string";
        //    }

        //    if (text == "string" && item.IsNullable && IsStringNullable)
        //    {
        //        text += "?";
        //    }

        //    if (item.OracleDataType.EqualCase("raw") && item.Length == 16)
        //    {
        //        return "Guid";
        //    }

        //    if (item.OracleDataType.EqualCase("number") && item.Length == 1 && item.Scale == 0)
        //    {
        //        return "bool";
        //    }

        //    if (text.EqualCase("char") || text.EqualCase("char?"))
        //    {
        //        return "string";
        //    }

        //    if (item.DataType == "tinyint unsigned")
        //    {
        //        return "short";
        //    }

        //    if (item.DataType == "smallint unsigned")
        //    {
        //        return "ushort";
        //    }

        //    if (item.DataType == "bigint unsigned")
        //    {
        //        return "ulong";
        //    }

        //    if (item.DataType == "int unsigned")
        //    {
        //        return "uint";
        //    }

        //    if (item.DataType == "MediumInt")
        //    {
        //        return "int";
        //    }

        //    if (item.DataType == "MediumInt unsigned")
        //    {
        //        return "uint";
        //    }

        //    return text;
        //}



        /// <summary>
        /// 测试连接
        /// </summary>
        /// <param name="dBConfig"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<object> TestConnect(DBConfig dBConfig)
        {

            var testDb = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = dBConfig.ConnectStr,
                DbType = dBConfig.EDBType,
                IsAutoCloseConnection = true
            });

            try
            {
                //执行简单的查询操作以测试连接
                testDb.Ado.CheckConnection();
            }
            catch (Exception ex)
            {
                return Msg.Error(ex.Message);
            }
            return Msg.Success(null);
        }
        //[HttpPost]
        //public override async Task<object> List([FromBody] QueryBase queryBase)
        //{
        //     base.List(queryBase);

        //    return null;
        //}
    }
}
